<template>
  <div>
    <input type="text" v-model="item">
    <button @click="addItem()">添加</button>
    <br>
    <hr>
    <h3>待完成</h3>
    <div>
        <span v-for="(item,index) in itemList" :key="item.item" v-show="!item.flag">
            <input type="checkbox" v-model="item.flag" @change="save()"> --- {{item.item}} --- <button @click="deleteItem(index)">删除</button>
        </span>
    </div>
    <h3>已完成</h3>
    <div>
        <span v-for="(item,index) in itemList" :key="item.item" v-show="item.flag">
            <input type="checkbox" v-model="item.flag" @change="save()"> --- {{item.item}} --- <button @click="deleteItem(index)">删除</button>
        </span>
    </div>
    <button @click="emitHeader()">给header广播数据</button>
  </div>
</template>

<script>
import {storage} from '../service/storage';
import VueEvent from '../service/vueEvent'
export default {
    name:'List',
    data(){
        return{
            item:'',
            itemList:[],
            msg:'这个List组件',
        }
    },
    methods:{
        emitHeader(){
            VueEvent.$emit('to-header',this.msg);
        },
        addItem(){
            //console.log(this.item,this.itemList)
            //console.log(this.isHaveItem(this.item,this.itemList))
            let arr = JSON.parse(JSON.stringify(this.itemList));
            console.log(arr);
            if(!this.isHaveItem(this.item,arr)){
                this.itemList.push({
                    item:this.item,
                    flag:false
                });
                let arr1 = JSON.parse(JSON.stringify(this.itemList));
                storage.set("todo",arr1);
            }
            this.item = "";
           
            //console.log(this.itemList)
        },
        isHaveItem(key,arr){
            console.log(key,arr);
            for(let i = 0;i<arr.length;i++){
                if(arr[i].item === key){
                    return true;
                }
            }
            return false;
        },
        deleteItem(index){
            this.itemList.splice(index,1);
            let arr = JSON.parse(JSON.stringify(this.itemList));
            storage.set("todo",arr);
        },
        save(){
             let arr = JSON.parse(JSON.stringify(this.itemList));
            storage.set("todo",arr);
        },
        
    },
    mounted(){
        console.log(storage.get("todo"))
        this.itemList = storage.get("todo") || [];
    }

}
</script>

<style scoped>

</style>
